package watcher

import (
	"github.com/shirou/gopsutil/mem"
	"time"
	"watcher/client/config"
)

type MemoryWatcher struct {
	Done     chan struct{}
	Duration time.Duration
}

func (watcher *MemoryWatcher) Watch() <-chan *WatchData {
	ch := make(chan *WatchData, 10)
	go watcher.watch(ch, watcher.Duration)
	return ch
}

func (watcher *MemoryWatcher) watch(ch chan<- *WatchData, duration time.Duration) {
	var t time.Time
	var ticker *time.Ticker
	ticker = time.NewTicker(duration)
	for {
		select {
		case t = <-ticker.C:
			func() {
				v, err := mem.VirtualMemory()
				if err != nil {
					return
				}
				ch <- &WatchData{
					Measurement: "memory",
					Time:        t,
					Fields: map[string]interface{}{
						"total": v.Total,
						"used":  v.Used,
					},
				}
			}()
		case <-watcher.Done:
			close(ch)
			ticker.Stop()
		}
	}
}

func (watcher *MemoryWatcher) Close() {
	close(watcher.Done)
}

func NewMemoryWatcher(conf config.Conf) (*MemoryWatcher, error) {
	return &MemoryWatcher{
		Done:     make(chan struct{}),
		Duration: conf.Duration,
	}, nil
}

var MemoryRegister = func(conf config.Conf) (string, Watcher, error) {
	wt, err := NewMemoryWatcher(conf)
	return "memory", wt, err
}
